<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small">
      <el-form-item label="手机/账号">
        <el-input
          v-model="queryParams.userName"
          style="width: 200px"
          clearable
          placeholder="请输入搜索关键词"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="list" v-loading="loading">
      <el-table-column prop="userName" label="管理系统账号名" />
      <el-table-column prop="nickName" label="管理系统昵称" />
      <el-table-column prop="phonenumber" label="管理系统手机号" />
      <el-table-column label="绑定状态" width="90" prop="type">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 1" type="success">已绑定</el-tag>
          <el-tag v-else type="danger">未绑定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="小程序头像">
        <template #default="{ row }">
          <el-image
            v-if="row.avatar != null && row.avatar != ''"
            style="width: 40px; height: 40px"
            :src="row.avatar"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="小程序手机号"></el-table-column>
      <el-table-column prop="bandTime" label="绑定时间" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="scope.row.mobile === null || scope.row.mobile === ''"
            size="small"
            type="text"
            @click="handleBand(scope.row)"
            >绑定</el-button
          >
          <el-button v-else size="small" type="text" @click="cancelBand(scope.row)"
            >解除绑定</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      v-model="bandOpen"
      title="绑定小程序用户"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="bandFormRef" :model="bandForm" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-select
            v-model="bandForm.userId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入手机号"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option v-for="item in options" :key="item.id" :label="item.mobile" :value="item.id">
              <span style="float: left">{{ item.nickName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.mobile }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场馆" prop="userName">
          <el-select
            v-model="bandForm.stadiumId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入场馆名"
            :remote-method="handleQueryStadium"
            :loading="loading"
          >
            <el-option
              v-for="item in stadiumOptions"
              :key="item.id"
              :label="item.stadiumName"
              :value="item.id"
            >
              <span style="float: left">{{ item.stadiumName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.stadiumName
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="bandOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { listUser, getMiniUser, bindUser, unbindUser } from '@/api/system/appUser'
import { getStadiumInfo } from '@/api/stadium/stadium'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义数据类型
interface UserItem {
  id: number
  userName: string
  nickName: string
  phonenumber: string
  type: number
  avatar: string
  mobile: string
  bandTime: string
  deptId: number
}

interface MiniUserItem {
  id: number
  mobile: string
  nickName: string
}

interface StadiumItem {
  id: number
  stadiumName: string
}

// 定义响应式数据
const loading = ref(false)
const total = ref(0)
const list = ref<UserItem[]>([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: undefined as string | undefined,
  phonenumber: undefined as string | undefined,
})

const bandOpen = ref(false)
const options = ref<MiniUserItem[]>([])
const stadiumOptions = ref<StadiumItem[]>([])

const bandData = ref<any>({})

const bandForm = reactive({
  id: null as number | null,
  userId: null as number | null,
  sysUserId: null as number | null,
  deptId: null as number | null,
  stadiumId: null as number | null,
})

// 表单引用
const queryFormRef = ref()
const bandFormRef = ref()

// 加载数据
const getList = () => {
  loading.value = true
  listUser(queryParams).then((res: any) => {
    loading.value = false
    total.value = res.total
    list.value = res.rows
  })
}

// 重置查询
const resetQuery = () => {
  queryParams.userName = ''
  getList()
}

// 处理绑定
const handleBand = (item: UserItem) => {
  bandOpen.value = true
  bandForm.sysUserId = item.id
  bandForm.deptId = item.deptId
}

// 解除绑定
const cancelBand = (item: UserItem) => {
  ElMessageBox.confirm('确认解除绑定吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      loading.value = true
      unbindUser(item).then((res: any) => {
        loading.value = false
        ElMessage.success('解除绑定成功')
        getList()
      })
    })
    .catch(() => {
      // 取消操作
    })
}

// 远程搜索小程序用户
const remoteMethod = (query: string) => {
  if (query !== '') {
    getMiniUser({ mobile: query }).then((res: any) => {
      options.value = res.data
    })
  } else {
    options.value = []
  }
}

// 查询场馆
const handleQueryStadium = (query: string) => {
  if (query !== '') {
    getStadiumInfo({ stadiumName: query }).then((res: any) => {
      stadiumOptions.value = res.data
    })
  } else {
    stadiumOptions.value = []
  }
}

// 提交表单
const submitForm = () => {
  if (bandForm.userId != null) {
    bindUser(bandForm).then((res: any) => {
      ElMessage.success('绑定成功')
      bandOpen.value = false
      getList()
    })
  } else {
    ElMessage.error('请选择用户')
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped></style>
